package com.onenine.chat.rongcloud;

import android.text.TextUtils;
import android.util.ArrayMap;

import com.onenine.app.request.RGroupRequest;
import com.onenine.app.response.RGroupResponse;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.chat.model.LGroup;
import com.onenine.common.util.Logger;
import com.onenine.common.util.StringUtils;

import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindCallback;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.List;

/**
 * 群聊信息缓存
 */
public class GroupCacheMgr {

    private static GroupCacheMgr mInstance;
    private ArrayMap<String, LGroup> mCacheMap;

    public interface OnGroupCallback {
        void callback(LGroup group);
    }

    public interface OnGroupsCallback {
        void callback(List<LGroup> groups);
    }

    private GroupCacheMgr() {
        mCacheMap = new ArrayMap<>();
    }

    public static GroupCacheMgr getInstance() {
        if (mInstance == null) {
            mInstance = new GroupCacheMgr();
        }
        return mInstance;
    }

    /**
     * 异步获取群组信息
     *
     * @param groupId
     * @param callback
     */
    public void getGroupAsync(String groupId, OnGroupCallback callback) {
        LGroup group = mCacheMap.get(groupId);
        if (group == null || TextUtils.isEmpty(group.getGroupName())) {
            getGroupFromDB(groupId, callback);
        } else {
            callback.callback(group);
        }
    }

    /**
     * 刷新群聊
     *
     * @param groupId
     */
    public void refreshGroupAsync(String groupId) {
        getGroupFromNetwork(groupId, new OnGroupCallback() {
            @Override
            public void callback(LGroup group) {
                Logger.e("刷新群聊：" + group);
            }
        });
    }

    /**
     * 从数据库读取群组
     *
     * @param groupId
     * @param callback
     */
    private void getGroupFromDB(final String groupId, final OnGroupCallback callback) {
        DataSupport.where("groupId=?", groupId).findLastAsync(LGroup.class).listen(new FindCallback() {

            @Override
            public <LGroup> void onFinish(LGroup t) {
                if (t == null) {
                    getGroupFromNetwork(groupId, callback);
                } else {
                    mCacheMap.put(groupId, (com.onenine.chat.model.LGroup) t);
                    callback.callback((com.onenine.chat.model.LGroup) t);
                }
            }
        });
    }

    /**
     * 从数据库读取群组
     *
     * @param callback
     * @param groupIds
     */
    private void getGroupsFromDB(final OnGroupsCallback callback, final String... groupIds) {
        DataSupport.where("groupId in (%s)", StringUtils.convertSet2DBCommaStr(groupIds)).findAsync(LGroup.class)
                .listen(new FindMultiCallback() {
                    @Override
                    public void onFinish(List t) {
                        if (callback != null) {
                            callback.callback(t);
                        }
                        for (int i = 0; i < t.size(); i++) {
                            LGroup group = (LGroup) t.get(i);
                            mCacheMap.put(group.getGroupId(), group);
                        }
                    }
                });
    }

    /**
     * 从网络下载群组信息
     *
     * @param groupId
     * @param callback
     */
    private void getGroupFromNetwork(final String groupId, final OnGroupCallback callback) {
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_GROUP_INFO)
                .withRequest(new RGroupRequest(RcUser.getInstance().getUserId(), groupId))
                .doRequest(GroupCacheMgr.class.getSimpleName(), new OkCallback<RGroupResponse>() {
                    @Override
                    public void onResponse(RGroupResponse response, String srcData) {
                        if (response.isSuccess()) {
                            LGroup group = new LGroup();
                            group.setGroupId(groupId);
                            group.setGroupName(response.getGroupName());
                            group.setGroupPhoto(response.getGroupPhoto());
                            group.setNoDisturb(response.getNoDisturb());
                            callback.callback(group);
                            mCacheMap.put(groupId, group);
                            if (!TextUtils.isEmpty(group.getGroupName())) {
                                //不可移除该日志
                                Logger.e("群聊信息缓存:" + group.saveOrUpdate("groupId=?", groupId));
                            }
                        } else {
                            callback.callback(null);
                        }
                    }
                });

    }

    /**
     * 删除指定群组缓存数据
     *
     * @param groupId
     */
    public void deleteGroupCacheByGroupId(String groupId) {
        mCacheMap.remove(groupId);
        DataSupport.deleteAll(LGroup.class, "groupId=?", groupId);
    }

}
